import rest_wrapper as rest
import logging
import sys
from flask import render_template, request, redirect, url_for, make_response
from frontend import app

ch = rest.CookieHandling()

## Initialize logging ##
file_handler = logging.FileHandler('logfile.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
app.logger.addHandler(file_handler)
# Example: app.logger.info('testje')

def rndr(template, **context):
    """ Wrapper around make_response and render_template to handle cookies and add session info from the backend. """

    def cursession():
        if rest.logged_in():
            s = dict()
            s['username'] = rest.get_username()
            return s

    # Forward backend's set_cookies to browser.
    try:
        response = make_response( render_template(template, session=cursession(), today=rest.get_todays_events(), **context) )
        if ch.get_backend_cookies():
            for c in ch.get_backend_cookies():
                print 'rndr: setting cookie to browser: %s = %s' % (c.name, c.value)
                response.set_cookie(key=c.name, value=c.value) # A Path may be required for deployment.
        return response

    except:
        return 'Backend error. %s ' % sys.exc_info()[1]

@app.route('/search')
def search():
    return rndr('search.html')

@app.route('/contact')
def contact():
    return rndr('contact.html')
    
@app.route('/about')
def about():
    return rndr('about.html')

@app.route('/')
def index():
    return rndr('landing.html',
        calendars=rest.get_calendars(),
        tokens=rest.get_tokens(),
        cookies=ch.get_client_cookies(),
        authlevel=rest.get_authlevel()

    )

@app.route('/calendar/<cal_id>/')
def show_calendar(cal_id):
    return rndr('show_calendar.html', calendar=rest.get_calendar(cal_id))

@app.route('/calendar/<cal_id>/event/<ev_id>/')
def show_event(cal_id, ev_id):
    return rndr('show_event.html', event=rest.get_event(cal_id, ev_id))

@app.route('/token/<token>', methods=['GET', 'POST'])
def personal_calendar(token):
    if token:
        try:
            token_id = rest.token_get_id(token)
        except:
            return redirect(url_for('page_not_found')) #TODO: FIX

        token_name = rest.token_get_name(token)
        tags = rest.token_get_tags(token_id)
        allfeeds = rest.get_calendars()
        tokenfeeds = rest.token_get_feeds(token_id)
        tokengroups = rest.token_get_groups(token_id)
        tokenorgs = rest.token_get_orgs(token_id)

        if request.method == 'POST':
            formfeeds = []
            formtags = []
            formgroups = []
            formorgs = []

            for item in request.form:
                if item.startswith('feed'):
                    formfeeds.append(item.split('_')[1])
                if item.startswith('tag'):
                    formtags.append(item.split('_')[1])
                if item.startswith('doelgroep'):
                    formgroups.append(item.split('_')[1])
                if item.startswith('org'):
                    formorgs.append(item.split('_')[1])

            # Add new tags
            for tag in formtags:
                if tag not in rest.token_get_tags(token_id):
                    rest.token_add_tag(token_id, tag)
            # Delete removed tags
            # If formdata is empty, remove all tags
            if not formtags:
                for tag in rest.token_get_tags(token_id):
                    rest.token_del_tag(token_id, tag)
            # Otherwise, remove specific tags
            else:
                for tag in rest.token_get_tags(token_id):
                    if tag not in formtags:
                        rest.token_del_tag(token_id, tag)

            # Add new feeds
            for feed_id in formfeeds:
                if feed_id not in rest.token_get_feeds(token_id):
                    rest.token_add_feed(token_id, feed_id)
            # Delete removed feeds
            for feed in rest.token_get_feeds(token_id):
                if str(feed[0]) not in formfeeds:
                    rest.token_del_feed(token_id, feed[0])

            # Add new groups
            for group in formgroups:
                if group not in rest.token_get_groups(token_id):
                    rest.token_add_group(token_id, group)
            # If formdata is empty, remove all groups
            if not formgroups:
                for group in rest.token_get_groups(token_id):
                    rest.token_del_group(token_id, group)
            # Otherwise, remove specific groups
            else:
                for group in rest.token_get_groups(token_id):
                    if group not in formgroups:
                        rest.token_del_group(token_id, group)

            # Add new orgs
            for org in formorgs:
                if org not in rest.token_get_orgs(token_id):
                    rest.token_add_org(token_id, org)
            # If formdata is empty, remove all orgs
            if not formorgs:
                for org in rest.token_get_orgs(token_id):
                    rest.token_del_org(token_id, org)
            # Otherwise, remove specific orgs
            else:
                for org in rest.token_get_orgs(token_id):
                    if org not in formorgs:
                        rest.token_del_org(token_id, org)



            # Fetch newly saved data
            tags = rest.token_get_tags(token_id)
            tokenfeeds = rest.token_get_feeds(token_id)
            tokengroups = rest.token_get_groups(token_id)
            tokenorgs = rest.token_get_orgs(token_id)

        return rndr('edittoken.html', token=token, name=token_name, feeds=allfeeds, tags=tags, tokenfeeds=tokenfeeds, doelgroepen=rest.get_doelgroepen(), tokengroups=tokengroups, tokenorgs=tokenorgs)

    else:
        # No token!
        return redirect(url_for('page_not_found'))

@app.route('/token/ical/<token>')
def ical(token):
    icaldata = rest.get_ical(token)
    return icaldata

@app.route('/signin/', methods=['GET', 'POST'])
def signin():
    if not rest.logged_in():
        if request.method == 'POST':
            if rest.signin(request.form['username'], request.form['password']):
                # Login succeeded, redirect to index page.
                return redirect(url_for('index'))
            else:
                return rndr('login_form.html', error='Onjuiste inloggegevens.')
        else:
            return rndr('login_form.html')
    else:
        # already logged in
        return redirect(url_for('index'))

@app.route('/signout/')
def signout():
    rest.signout()
    return redirect(url_for('index'))

### Error pages ###

@app.errorhandler(404)
def page_not_found(e):
    return rndr('404.html')

@app.errorhandler(500)
def server_error(e):
    return rndr('500.html')